﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using AutoTestingFramework.Core.Configurations;
using System.Configuration;

using AutoTestingFramework.Utilities.JsonHelper;

namespace AutoTestingFramework.Core.WebDrivers
{
    public class WebDriverBootstrap
    {
        private IWebBroswerFactory _webBroswerFactory;
        private IWebDriverSettings _webDriverSettings;

        public static WebDriverBootstrap Bootstrapper = new WebDriverBootstrap();

        public WebDriverBootstrap()
        {
            _webBroswerFactory = new WebBroswerFactory();
            _webDriverSettings = new WebDriverSettings();
        }

        public IWebDriver Start()
        {
            //read config file which broswer should be started, otherwise, default start IE.
            string configuredWebBroswer = ConfigurationManager.AppSettings["browser"];

            string remoteSettingFileLocation = ConfigurationManager.AppSettings["DesiredCapLoc"];
            string hubURL = ConfigurationManager.AppSettings["HubURL"];

            if (!string.IsNullOrWhiteSpace(configuredWebBroswer))
            {   
                WebBroswerType webBroswerType;
                if (Enum.TryParse<WebBroswerType>(configuredWebBroswer,out webBroswerType))
                {
                    if(webBroswerType==WebBroswerType.Remote)
                    {
                        _webDriverSettings.HubURL = new Uri(hubURL);
                        Capabilties capabilities = JsonHelper.Deserialize<Capabilties>(remoteSettingFileLocation);
                        _webDriverSettings.BrowserCapability = capabilities.Capabilities[0];
                    }
                    return Start(webBroswerType);
                }
                
            }
            return Start(WebBroswerType.IE);
        }

        public IWebDriver Start(WebBroswerType webBroswerType)
        {
            return Start(webBroswerType, _webDriverSettings);
        }

        public IWebDriver Start(WebBroswerType webBroswerType, IWebDriverSettings settings)
        {
            var webDriverFactory = _webBroswerFactory.GenerateBrowserSpecificDriver(webBroswerType, settings);

            var webDriver = webDriverFactory();

            return webDriver;
        }




    }
}
